﻿#region
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Design.PluralizationServices;
using System.Deployment.Application;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using EdmxTransformer.Components;
using EdmxTransformer.Properties;

#endregion

namespace EdmxTransformer.Forms
{
    public partial class MainForm : BaseForm
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private PluralizationService _pluralization;

        #region form event handlers
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (DesignMode)
                return;

            _pluralization = PluralizationService.CreateService(new CultureInfo("en-US"));

//            var rowAddableGrids = new[] {dgvPropertySubstituion, dgvPrefixSubstituion, dgvPostfixSubstituion};
//            foreach (var grid in rowAddableGrids)
//                grid.AllowUserToAddRows = true;

            if (string.IsNullOrEmpty(Settings.Default.InitialDirectoryForET))
                Settings.Default.InitialDirectoryForET = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            if (string.IsNullOrEmpty(Settings.Default.InitialDirectoryForEdmx))
                Settings.Default.InitialDirectoryForEdmx = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

#if DEBUG
            ofdET.InitialDirectory = @"d:\tfs\NewHowMuch-마스터통합\Files";
            ofdEdmx.InitialDirectory = @"D:\tfs\NewHowMuch-마스터통합\NewHowMuch.Data";
//            ofdEdmx.InitialDirectory = @"d:\tfs\NewHowMuch-마스터통합\NewHowMuch.Data\";
//            ofdEdmx.InitialDirectory = @"D:\tfs\NewHowMuch-마스터통합\NewHowMuch.Data.EdmxTransformation";
//            ofdEdmx.InitialDirectory = @"D:\Practices\ConsoleApplication1\ConsoleApplication1";
#endif
            sfdET.InitialDirectory = ofdET.InitialDirectory;

#if DEBUG
//            meiNew.PerformClick();
         meiOpen.PerformClick();
//            meiTransformToTarget.PerformClick();
//            meiRefreshSchema.PerformClick();
#endif
            Text += " - " + GetVersion();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            Settings.Default.Save();

            base.OnClosing(e);
        }
        #endregion

        #region menu item event handlers
        private void meiNew_Click(object sender, EventArgs e)
        {
            if (ofdEdmx.ShowDialog() != DialogResult.OK)
                return;

            _schema.Clear();
            _schema.Edmx.AddEdmxRow(ofdEdmx.FileName);

            RefreshSchema();
        }

        private void meiOpen_Click(object sender, EventArgs e)
        {
            if (ofdET.ShowDialog() == DialogResult.OK)
            {
                ReadXml();
            }
        }

        private void meiSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(sfdET.FileName))
            {
                meiSaveAs.PerformClick();
            }
            else
            {
                _schema.WriteXml(sfdET.FileName);
            }
        }

        private void meiSaveAs_Click(object sender, EventArgs e)
        {
            if (sfdET.ShowDialog() == DialogResult.OK)
            {
                WriteXml();
            }
        }

        private void meiExit_Click(object sender, EventArgs e)
        {
            if (WinformUtility.Ask("Are you sure to exit?"))
                Close();
        }

        private void meiRefreshSchema_Click(object sender, EventArgs e)
        {
            if (ValidateEdmxPath() == false)
                return;

            RefreshSchema();

//            MessageBox.Show("Schema have been refreshed");
        }

        private void meiApplyRule_Click(object sender, EventArgs e)
        {
            EdmxHelper.ApplyRules(_schema);

//            MessageBox.Show("Rules have been applied");
        }

        private void meiTransformEdmx_Click(object sender, EventArgs e)
        {
            if (ValidateEdmxPath() == false)
                return;

            if (WinformUtility.Ask("Are you sure to transform target EDMX file? The file will be OVERWRITTEN") == false)
                return;

            EdmxHelper.Transform(_schema.Edmx[0].Path, _schema);

            MessageBox.Show("EDMX has transformed");
        }

        private void meiAbout_Click(object sender, EventArgs e)
        {
            var version = GetVersion();
            MessageBox.Show(version.ToString());
        }

        private void meiHelp_Click(object sender, EventArgs e)
        {
        }
        #endregion

        #region grid event handlers
        private void dgvEntity_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != 1 || e.RowIndex < 0)
                return;

            dgvEntity[2, e.RowIndex].Value = _pluralization.Pluralize(dgvEntity[1, e.RowIndex].Value.ToString());
        }
        #endregion

        #region event handlers
        private void btnBrowseEdmx_Click(object sender, EventArgs e)
        {
            if (ofdEdmx.ShowDialog() != DialogResult.OK)
                return;

            if (_schema.Edmx.Count == 0)
                _schema.Edmx.AddEdmxRow(ofdEdmx.FileName);
            else
                _schema.Edmx[0].Path = ofdEdmx.FileName;

        }
        #endregion

        #region methods
        private void ReadXml()
        {
            _schema.Clear();
            _schema.ReadXml(ofdET.FileName);
        }

        private void WriteXml()
        {
            _schema.WriteXml(sfdET.FileName);
        }

        private void RefreshSchema()
        {
            EdmxSchema newSchema = EdmxHelper.ExtractSchema(_schema.Edmx[0].Path);
            _schema.RefreshSchema(newSchema);
        }

        private bool ValidateEdmxPath()
        {
            if (_schema.Edmx.Count == 0 || File.Exists(_schema.Edmx[0].Path) == false)
            {
                MessageBox.Show("Invalid EDMX Path");
                return false;
            }
            else
                return true;
        }

        private Version GetVersion()
        {
            Version version = ApplicationDeployment.IsNetworkDeployed
                ? ApplicationDeployment.CurrentDeployment.CurrentVersion
                : Assembly.GetEntryAssembly().GetName().Version;
            return version;
        }
        #endregion

        private void MainForm_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.PageUp)
                tbcTab.SelectedIndex = 0;
            else if (e.KeyCode == Keys.PageDown)
                tbcTab.SelectedIndex = 1;
        }
    }
}